package com.hd.trans.framework.dialog;

import android.app.Dialog;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.entity.node.BaseNode;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.android.material.tabs.TabLayout;
import com.hd.trans.R;
import com.hd.trans.db.DataBaseMgr;
import com.hd.trans.db.bean.HuDunLanguage;
import com.hd.trans.db.bean.LanguageGroup;
import com.hd.trans.network.PreferenceMgr;
import com.hd.trans.utils.DensityUtils;
import com.hd.trans.widgets.LetterSlideView;

import java.util.ArrayList;
import java.util.List;

public class SelectVoiceLanguageDialog extends DialogFragment implements OnItemClickListener {

    private TabLayout tabLayout;
    private RecyclerView recyclerView;
    private LetterSlideView sidleLetter;

    private static final String ARG_IS_FROM = "arg_is_from";
    private static final String ARG_FROM_LAN = "arg_from_lan";
    private static final String ARG_TO_LAN = "arg_to_lan";

    private HuDunLanguage fromLanguage, toLanguage;
    private LanguageDialogAdapter adapter;
    private boolean isFromPage = true;
    private Handler handler;
    private OnLanguageChangedListener mOnLanguageChangedListener;
    private TextView tvLetter;
    private ArrayList<BaseNode> newList;  //列表数据
    private ArrayList<String> letters;//字母列表
    private LanguageGroup groupHot;


    public interface OnLanguageChangedListener {
        void onLanguageChanged(HuDunLanguage language, boolean isFrom);
    }

    public SelectVoiceLanguageDialog setOnLanguageChangedListener(OnLanguageChangedListener onLanguageChangedListener) {
        this.mOnLanguageChangedListener = onLanguageChangedListener;
        return this;
    }

    public static SelectVoiceLanguageDialog newInstance(HuDunLanguage fromLanguage, HuDunLanguage toLanguage, boolean isFromPage) {
        SelectVoiceLanguageDialog instance = new SelectVoiceLanguageDialog();
        Bundle args = new Bundle();
        args.putParcelable(ARG_FROM_LAN, fromLanguage);
        args.putParcelable(ARG_TO_LAN, toLanguage);
        args.putBoolean(ARG_IS_FROM, isFromPage);

        instance.setArguments(args);
        return instance;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置dialog样式
        setStyle(DialogFragment.STYLE_NO_TITLE, R.style.BottomDialogStyle);
    }

    @Override
    public void onStart() {
        super.onStart();
        //可以在createView里一次写
        Dialog dialog = getDialog();
        //设置dialog 宽高
        if (dialog != null) {
            int width = Resources.getSystem().getDisplayMetrics().widthPixels;
            dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            dialog.getWindow().setGravity(Gravity.BOTTOM);
        }
    }


    private void initDialog() {
        Dialog dialog = getDialog();
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));//设置背景为透明
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_select_language_layout, container, false);
        initView(view);
        initDialog();
        initData();
        return view;
    }

    private void initData() {
        Bundle args = getArguments();
        if (args != null) {
            fromLanguage = args.getParcelable(ARG_FROM_LAN);
            toLanguage = args.getParcelable(ARG_TO_LAN);
            isFromPage = args.getBoolean(ARG_IS_FROM);
        }

        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        //设置item间距
        recyclerView.addItemDecoration(
                new LanguageItemDecoration(
                        DensityUtils.dip2px(
                                getContext(),
                                3f
                        )
                )
        );
        adapter = new LanguageDialogAdapter();
        //设置条目加载动画。
        adapter.setAnimationEnable(true);
        adapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.SlideInBottom);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(this);

        //从数据库中初始化语音列表。
        initLanguages();

        tabLayout.getTabAt(0).select();
        if (isFromPage) {
            tabLayout.getTabAt(0).select();
        } else {
            tabLayout.getTabAt(1).select();
        }
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getPosition() == 0) {
                    isFromPage = true;
                } else {
                    isFromPage = false;
                }
                initLanguages();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        sidleLetter.setOnTouchingChangedListener(new LetterSlideView.OnTouchingChangedListener() {
            @Override
            public void onTouchingChanged(String str) {
                int index = 0;
                for (int i = 0; i < adapter.getData().size(); i++) {
                    BaseNode item = adapter.getData().get(i);
                    if (item instanceof LanguageGroup) {
                        if (str.equals(((LanguageGroup) item).getName())) {
                            index = i;
                            break;
                        }
                    } else {
                        continue;
                    }
                }
//                Logger.i("===========index : "+index);
                ((LinearLayoutManager) recyclerView.getLayoutManager()).scrollToPositionWithOffset(index, 0);
                ((LinearLayoutManager) recyclerView.getLayoutManager()).setStackFromEnd(true);
//                recyclerView.scrollToPosition( index );

                tvLetter.setText(str);
                tvLetter.setVisibility(View.VISIBLE);
                if (handler == null) {
                    handler = new Handler();
                }
                handler.removeCallbacks(overlayThread);
                handler.postDelayed(overlayThread, 500);
            }
        });
    }

    private void initView(View view) {
        tabLayout = (TabLayout) view.findViewById(R.id.top_tab);
        recyclerView = (RecyclerView) view.findViewById(R.id.language_recycler);
        sidleLetter = (LetterSlideView) view.findViewById(R.id.sidleLetter);
        tvLetter = (TextView) view.findViewById(R.id.tv_letter);
        tabLayout.addTab(tabLayout.newTab().setText("源语言"), 0);
        tabLayout.addTab(tabLayout.newTab().setText("目标语言"), 1);
    }


    private void initLanguages() {
        //数据库获取语言列表
        List<LanguageGroup> groupList = DataBaseMgr.getInstance().getLanguageGroups(isFromPage ? toLanguage : fromLanguage);

        //创建新的数据列表
        if (null == newList) {
            newList = new ArrayList<>(groupList);
        } else {
            newList.clear();
            newList.addAll(groupList);
        }
        //把新的数据给adapter。
        adapter.setNewData(newList);
        sidleLetter.setLetterList(null);
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter mAdapter, @NonNull View view, int position) {
        Object item = adapter.getItem(position);
        if (item instanceof HuDunLanguage) {
            HuDunLanguage checkedItem = (HuDunLanguage) item;
            if (checkedItem != null) {
                if (!checkedItem.equals(adapter.getCheckedItem())) {
                    if (mOnLanguageChangedListener != null)
                        mOnLanguageChangedListener.onLanguageChanged(checkedItem, isFromPage);
                    /*if(isFromPage){
                        PreferenceMgr.getInstance().getTranslatePreference().saveVoiceFromLanguage(checkedItem.getName());
                    }else {
                        PreferenceMgr.getInstance().getTranslatePreference().saveVoiceToLanguage(checkedItem.getName());
                    }*/
                }
                dismiss();
            }
        }
    }

    /* 触摸右侧拼音 */
    private OverlayThread overlayThread = new OverlayThread();

    private class OverlayThread implements Runnable {

        public void run() {
            tvLetter.setVisibility(View.GONE);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (handler != null) {
            handler.removeCallbacks(null);
            handler = null;
        }
    }
}
